#include "map.h"
#include <stdio.h>

typedef enum {
    Right,
    Down,
    Left,
    Up
} Direction;

static void printPath (Robot robot, Node exit);

int main () {
    Robot robot;
    robot.x = 0;
    robot.y = 0;
    Node exit;
    exit.x = 1;
    exit.y = 2;
    printf("简单的小题\n");
    printf("两分钟搞定\n");
    printf("菜就多练\n");
    printPath(robot, exit);
    return 0;
}

static void printPath (Robot robot, Node exit) {
    Direction direct = Right;
    int order[3] = {0};
    while (robot.x != exit.x || robot.y != exit.y) {
        printf("(%d, %d)\n", robot.x, robot.y);
        if (direct == Right) {
            // 如果是向右，则先看看能不能向上
            if (robot.x != 0 && g_map[robot.x-1][robot.y] != 1) {
                robot.x--;
                direct = Up;
                continue;
            } else {
                order[0] = Right;
                order[1] = Down;
                order[2] = Left;
            }
        } else if (direct == Down) {
            // 如果是向下，则先看看能不能向右
            if (robot.y != COL-1 && g_map[robot.x][robot.y+1] != 1) {
                robot.y++;
                direct = Right;
                continue;
            } else {
                order[0] = Down;
                order[1] = Left;
                order[2] = Up;
            }
        } else if (direct == Left) {
            // 如果是向左，则先看看能不能向下
            if (robot.x != ROW-1 && g_map[robot.x+1][robot.y] != 1) {
                robot.x++;
                direct = Down;
                continue;
            } else {
                order[0] = Left;
                order[1] = Up;
                order[2] = Right;
            }
        } else if (direct == Up) {
            // 如果是向上，则先看看能不能向左
            if (robot.y != 0 && g_map[robot.x][robot.y-1] != 1) {
                robot.y--;
                direct = Left;
                continue;
            } else {
                order[0] = Up;
                order[1] = Right;
                order[2] = Down;
            }
        }
        
        for (int i=0; i<3; i++) {
            direct = (Direction)order[i];
            if (order[i] == Left && robot.y > 0 && g_map[robot.x][robot.y-1] != 1) {
                robot.y--;
                break;
            } else if (order[i] == Down && robot.x < ROW - 1 && g_map[robot.x+1][robot.y] != 1) {
                robot.x++;
                break;
            } else if (order[i] == Right && robot.y < COL - 1 && g_map[robot.x][robot.y+1] != 1) {
                robot.y++;
                break;
            } else if (order[i] == Up && robot.x > 0 && g_map[robot.x-1][robot.y] != 1) {
                robot.x--;
                break;
            }
        }
    }
    printf("(%d, %d)\n", robot.x, robot.y);
}